/*数据库操作*/
/*http请求*/
const rp = require('request-promise');
/*登录信息校验*/
const tokenvilidate = require('../../common/tokenvilidate.js');
/*数据库工具*/
const basics_db = require('../../dbhelper/basics_db.js');
/*淘宝客工具*/
const tbkUtil = require('../../../utils/tbk_util.js');
/*通用工具*/
const jason_tools = require('../../../utils/jason_tools.js');

/*根参数*/
const appkey = '28243418';
const appsecret = '8acfffd32b0f66ebaae5863ef57ab771';
const pid = 'mm_113916518_1166900193_110146300461';
/* 淘宝官方 */
const uri = 'http://gw.api.taobao.com/router/rest';
/* 维易淘宝客API */
const WYzluri = 'http://api.vephp.com/hcapi';
const WYsuper = 'http://apis.vephp.com/super';
const WYOrderuri = 'http://apiorder.vephp.com/order';
const WYTbcats = 'http://api.vephp.com/tbcats';
const WYvekey = 'V00001109Y18343095';

/**
 * Sign API request.
 * see http://open.taobao.com/doc/detail.htm?id=111#s6
 *
 * @param  {Object} params
 * @return {String} sign string
 */
function sign(params) {
    var sorted = Object.keys(params).sort();
    var basestring = appsecret;
    for (var i = 0, l = sorted.length; i < l; i++) {
        var k = sorted[i];
        basestring += k + params[k];
    }
    basestring += appsecret;
    return tbkUtil.md5(basestring).toUpperCase();
};


/**
 * @api {get} /tb_tbk/optional 通用物料搜索API（导购）
 * @apiName optional
 * @apiGroup tb_tbk
 *
 * @apiParam {String} q 搜索关键字.
 * @apiParam {String} platform 平台 默认2.
 * @apiParam {String} sort 排序方式.
 * @apiParam {Boolean} has_coupon 是否搜索含有优惠券.
 * @apiParam {String} page_no 页数.
 * @apiParam {String} page_size 条数.
 *
 * @apiSuccess {String} code 200 数据成功.
 * @apiSuccess {Object} result  数据结果对象.
 */

exports.optional = async (ctx, next) => {
    // /*参数声明*/
    let query = ctx.query;
    // /*检验身份*/
    // let tokenRes = await tokenvilidate.tokenCheck(tokens);
    // if (!tokenRes.ok) {
    //     return ctx.body = tokenRes
    // }
    // /*vip报酬*/
    // let vip = tokenRes.data.vip;
    // let vipReward = 0.5;

    // switch (vip) {
    //     case 0:
    //         vipReward = 0.5;
    //         break;
    //     case 0:
    //         vipReward = 0.52;
    //         break;
    //     case 0:
    //         vipReward = 0.55;
    //         break;
    //     case 0:
    //         vipReward = 0.6;
    //         break;
    //     case 0:
    //         vipReward = 0.7;
    //         break;
    //     case 0:
    //         vipReward = 0.8;
    //         break;
    //     default:
    //         vipReward = 0.5;
    //         break;
    // }

    /*传参声明*/
    let params = {
        app_key: appkey,
        sign_method: 'md5',
        format: 'json',
        v: '2.0',
        timestamp: tbkUtil.YYYYMMDDHHmmss(),
        method: 'taobao.tbk.dg.material.optional',
        fields: 'num_iid,title,pict_url,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,tk_comm_fee,tk_common_fee,'
    };
    Object.assign(params, query);

    params.adzone_id = pid.split('_')[3];
    /*签名*/
    params.sign = sign(params);

    /*函数体*/
    let options = {
        uri: uri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

 /**
 * @api {get} /tb_tbk/material 淘宝客物料下行导购（好券推荐）
 * @apiName material
 * @apiGroup tb_tbk
 *
 * @apiParam {String} val 搜索关键字.
 *
 * @apiSuccess {Object} tbk_dg_optimus_material_response  数据结果对象.
 * 
 * @apiSuccessExample Success-Response:
 * tbk_dg_optimus_material_response: {is_default: "false",…}
 * is_default: "false"
 * request_id: "6bwme2f5ekz0"
 * result_list: {map_data: [{category_id: 127684027,…}, {category_id: 50006846,…}, {category_id: 50010535,…},…]}
 */

exports.material = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    /*传参声明*/
    let params = {
        app_key: appkey,
        sign_method: 'md5',
        format: 'json',
        v: '2.0',
        timestamp: tbkUtil.YYYYMMDDHHmmss(),
        method: 'taobao.tbk.dg.optimus.material'
    };

    params.adzone_id = pid.split('_')[3]

    // adzone_id


    Object.assign(params, query);
    /*签名*/
    params.sign = sign(params);

    /*函数体*/
    let options = {
        uri: uri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

/**
 * 维易超级搜索（只对比数据没有进行使用）
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.WYsuperList = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    /*传参声明*/
    let params = {
        vekey: WYvekey
    };

    Object.assign(params, query);
    params.adzone_id = pid.split('_')[3]

    /*函数体*/
    let options = {
        uri: WYsuper,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

/**
 * 维易商品链接转换（转链 -- 直达领券）
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.WYsuperSearch = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    /*传参声明*/
    let params = {
        vekey: WYvekey,
        detail: '1',
        para: query.para || ''
    };

    params.pid = pid

    /*函数体*/
    let options = {
        uri: WYzluri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise'
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = repos;
        })
        .catch(function (err) {
            res = err;
        });

    return ctx.body = res;
}

/**
 * 淘宝二级分类
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getTbcats = async (ctx, next) => {

    let data = await basics_db.find('cats', {})

    return ctx.body = data;
}

/**
 * 数据通讯测试
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.dataTest = async (ctx, next) => {
    return ctx.body = ctx;
}
